package com.wing.device.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.dict.model.entity.DictLabel;
import com.wing.dict.service.DictLabelService;
import com.wing.product.model.response.ProductTypeVO;
import com.wing.product.service.ProductTypeService;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.device.model.entity.*;
import com.wing.device.model.request.DeviceForm;
import com.wing.device.model.response.DeviceVO;
import com.wing.device.service.*;
import com.wing.product.model.entity.ProductDetail;
import com.wing.purchase.model.entity.SupplierInfo;
import com.wing.purchase.service.SupplierInfoService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.CompanyInfoVO;
import com.wing.user.model.response.DepartmentVO;
import com.wing.utils.ExcelUtils;
import com.wing.web.excel.DeviceExcelIn;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.UserExcelIn;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-设备表管理", tags = "#/device/device")
@RestController("deviceController")
@RequestMapping("device/admin/device")
@Slf4j
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private DeviceTypeService deviceTypeService;

    @Autowired
    private DeviceCategoryService deviceCategoryService;

    @Autowired
    private DeviceModelService deviceModelService;

    @Autowired
    private SupplierInfoService supplierInfoService;
    @Autowired
    private DeviceBrandService deviceBrandService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private DictLabelService dictLabelService;

    @Autowired
    private DeviceWorkshopService deviceWorkshopService;



    @ApiOperation(value = "查询所有设备表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value="设备名称", defaultValue = "name", example = "name", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "deviceCode", value="设备编码", defaultValue = "deviceCode", example = "deviceCode", dataType = "String", paramType = "query")

    })
    @GetMapping("/list")
    public PageResult<DeviceVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "sort_number") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,@RequestParam(defaultValue = "") String name
            ,@RequestParam(defaultValue = "")String deviceCode
            ,Long deviceType
            ,Long deviceTypeId
            ,Long categoryId
            ,String startTime
            ,String endTime
            ,Long workshopId
            ,String deviceModel
            ,String deviceModelId
    ){

        Page<DeviceVO> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
//        paramMap.put("sort",StrUtil.toUnderlineCase(sort));
//        paramMap.put("order",StrUtil.toUnderlineCase(order));
        paramMap.put("name",name);
        paramMap.put("deviceCode",deviceCode);
        //搜索
        if (deviceType!=null){
            paramMap.put("deviceType",deviceType);
        }
        if (deviceTypeId!=null){
            paramMap.put("deviceTypeId",deviceTypeId);
        }
        if (categoryId!=null){
            paramMap.put("categoryId",categoryId);
        }
        if(workshopId!=null){
            paramMap.put("workshopId",workshopId);
        }
        if(deviceModel!=null){
            paramMap.put("deviceModel",deviceModel);
        }
        if(deviceModelId!=null){
            paramMap.put("deviceModelId",deviceModelId);
        }
        paramMap.put("startCreateTime",startTime);
        paramMap.put("endCreateTime",endTime);

        Page<DeviceVO> list = deviceService.pageList4app(pg, paramMap);

        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加设备表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(DeviceForm.Update.class) DeviceForm deviceForm)  {
        try{

            deviceService.save(deviceForm);
            return JsonResult.success("添加成功");
        }catch (Exception e){
            log.error("add device fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }




    @ApiOperation(value = "修改设备表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(DeviceForm.Update.class) DeviceForm deviceForm) {
        Device device = deviceService.getById(deviceForm.getId());
        if(device == null){
            return JsonResult.fail("修改失败！");
        }
        if(StringUtils.isNotBlank(deviceForm.getSupplierId())){
            SupplierInfo supplierInfo = supplierInfoService.getById(deviceForm.getSupplierId());
            device.setSupplierName(supplierInfo.getCorporateName());
        }
        //修改附件
        deviceService.updateEnclosure(device.getId(),deviceForm.getEnclosureUrl());
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(Device.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(deviceForm, device, copyOptions);
        if (deviceService.updateById(device)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除设备表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "设备表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long deviceId) {

        if (deviceService.removeById(deviceId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @PreAuthorize("hasAuthority('delete:/device/admin/device/batchIds')")
    @ApiOperation(value = "批量删除资产类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "设备ids", required = true, dataType = "Long", paramType = "path")
    })
    @DeleteMapping("/batchIds")
    public JsonResult batchDelete(@RequestParam("ids[]") Long[] ids) {

        if (deviceService.getBaseMapper().deleteBatchIds(Arrays.asList(ids)) > 0) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询所有设备", notes = "查询")
    @GetMapping("/getAll")
    public JsonResult<Device> getAll(){

        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.select("id","device_code","name");
        List<Device> device = deviceService.list(wrapper);
        return JsonResult.success(device);
    }

    @ApiOperation(value = "根据id查询设备", notes = "查询")
    @GetMapping("/getDeviceById")
    public JsonResult<DeviceVO> getDeviceById(Long id){

        DeviceVO deviceVO = deviceService.get4appById(id);
        return JsonResult.success(deviceVO);
    }
   /* @ApiOperation(value = "查询工序设备中没有的设备", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value="设备名称", defaultValue = "name", example = "name", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "deviceCode", value="设备编码", defaultValue = "deviceCode", example = "deviceCode", dataType = "String", paramType = "query")

    })
    @GetMapping("/processList")
    public PageResult<DeviceVO> processList(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "sort_number") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,@RequestParam(defaultValue = "") String name
            ,@RequestParam(defaultValue = "")String deviceCode
    ){

        Page<DeviceVO> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
        paramMap.put("sort",StrUtil.toUnderlineCase(sort));
        paramMap.put("order",StrUtil.toUnderlineCase(order));
        paramMap.put("name",name);
        paramMap.put("deviceCode",deviceCode);
        //搜索
        Page<DeviceVO> list = deviceService.pageListProcess(pg, paramMap);

        return new PageResult<>(list.getRecords(), list.getTotal());
    }*/

    /**
     * 下载设备数据录入excel模板
     */
    @ApiOperation(value = "下载设备数据录入excel模板")
    @GetMapping("/deviceTemplate")
    public void deviceTemplate(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"设备名称(*)","设备编码(*)","资产编码(*)","设备分类","设备类型","设备型号","设备品牌",
                "所属企业(*)","设备供应商","待折旧金额","待折旧时长","开始折旧时间","上次年检时间","下次年检时间","年检周期",
                "上次维护时间","下次维护时间","维保周期","车间","部门"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        //设备类型
        StringBuffer tempStr = new StringBuffer();
        Map<String, Object> productTypeParams = new HashMap<>();
        //类别性质
        QueryWrapper<DictLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type", "sys_device_type_code");
        List<DictLabel> dictLabelList = dictLabelService.list(queryWrapper);
        if(CollectionUtil.isNotEmpty(dictLabelList)){
            productTypeParams.put("parentId",dictLabelList.get(0).getLabelValue());
        }
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (org.apache.commons.lang.StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        productTypeParams.put("databaseUser", databaseUser);
        List<ProductTypeVO> deviceTypeList = productTypeService.list4app(productTypeParams);
        if(CollectionUtil.isNotEmpty(deviceTypeList)){
            for (ProductTypeVO deviceType : deviceTypeList) {
                tempStr.append(deviceType.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("4");
        }
        //设备分类
        QueryWrapper<DeviceCategory> deviceCategoryWrapper = new QueryWrapper<DeviceCategory>();
        deviceCategoryWrapper.eq("is_deleted", 1);
        List<DeviceCategory> deviceCategoryList = deviceCategoryService.list(deviceCategoryWrapper);
        if(CollectionUtil.isNotEmpty(deviceCategoryList)){
            for (DeviceCategory deviceCategory : deviceCategoryList) {
                tempStr.append(deviceCategory.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("3");
        }
        //设备型号
        List<DeviceModel> deviceModelList = deviceModelService.list();
        if(CollectionUtil.isNotEmpty(deviceModelList)){
            for (DeviceModel deviceModel : deviceModelList) {
                tempStr.append(deviceModel.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("5");
        }
        //设备品牌
        List<DeviceBrand> deviceBrandList = deviceBrandService.list();
        if(CollectionUtil.isNotEmpty(deviceBrandList)){
            for (DeviceBrand deviceBrand : deviceBrandList) {
                tempStr.append(deviceBrand.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("6");
        }
        //所属企业
        JsonResult<List<CompanyInfoVO>> companyInfoList = userClient.getCompanyInfoList();
        List<CompanyInfoVO> infoVOList = companyInfoList.getData();
        if(CollectionUtil.isNotEmpty(infoVOList)){
            for (CompanyInfoVO companyInfoVO :infoVOList) {
                tempStr.append(companyInfoVO.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("7");
        }
        // 供应商
        QueryWrapper<SupplierInfo> wrapper = new QueryWrapper<>();
        wrapper.select("id", "corporate_name");
        wrapper.eq("status", SupplierInfo.Status.pass);
        List<SupplierInfo> supplierInfoList = supplierInfoService.list(wrapper);
        if(CollectionUtil.isNotEmpty(supplierInfoList)){
            for (SupplierInfo supplierInfo :supplierInfoList) {
                tempStr.append(supplierInfo.getCorporateName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("8");
        }

        //获取所有车间信息
        Page<DeviceWorkshop> pg = new Page<>(1, 999);
        QueryWrapper<DeviceWorkshop> queryWrapper2 = new QueryWrapper<>();

        IPage<DeviceWorkshop> list2 = deviceWorkshopService.getBaseMapper().selectPage(pg, queryWrapper2);
        List<DeviceWorkshop> deviceWorkshopList = list2.getRecords();
        if(CollectionUtil.isNotEmpty(deviceWorkshopList)){
            for (DeviceWorkshop companyInfoVO :deviceWorkshopList) {
                tempStr.append(companyInfoVO.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("18");
        }


        //获取所有部门信息 userClient
        JsonResult treeData = userClient.getTreeData(null, null);
        Object data = treeData.getData();
        List<String> departList = new ArrayList<>();
        if (data instanceof List) {
            extractNames(data, departList);
       }


        if(CollectionUtil.isNotEmpty(departList)){
            for (String departName :departList) {
                tempStr.append(departName).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("19");
        }

        DownExcelUtil.createExcelTemplate(response, request, "设备导入模板", Arrays.asList(headerArr), downData, indexArr);
    }


    public void extractNames(Object data, List<String> departList) {
        if (data instanceof List) {
            @SuppressWarnings("unchecked")
            List<LinkedHashMap<String, Object>> dataList = (List<LinkedHashMap<String, Object>>) data;

            for (LinkedHashMap<String, Object> item : dataList) {
                // 提取当前节点的 name
                if (item.containsKey("name")) {
                    String name = (String) item.get("name");
                    departList.add(name);
                }

                // 递归处理 children
                Object children = item.get("children");
                if (children instanceof List) {
                    extractNames(children, departList);
                }
            }
        }
    }








    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<DeviceExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<DeviceExcelIn> list = reader.read(is, DeviceExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            deviceService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

    @ApiOperation(value = "单个添加", notes = "添加")
    @PostMapping("/addDevice")
    public JsonResult addDevice(DeviceForm deviceForm){
        Device one = deviceService.getOne(new LambdaQueryWrapper<Device>().eq(Device::getDeviceCode, deviceForm.getDeviceCode()));
        if(one!=null){
            return JsonResult.fail("设备编号已存在，请重新输入！");
        }
        Device device = new Device();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(Device.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(deviceForm, device, copyOptions);
        if(device.getSupplierId()!=null){
            SupplierInfo supplierInfo = supplierInfoService.getById(device.getSupplierId());
            device.setSupplierName(supplierInfo.getCorporateName());
        }
        device.setStatus(Device.Status.normalUse);
        if (deviceService.save(device)) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }
    @ApiOperation(value = "设备导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response, String startCreateTime, String endCreateTime, String enterpriseCode){
        List<DeviceVO> list = new ArrayList<>();
        if ("".equals(startCreateTime) || "".equals(endCreateTime)){
            log.error("创建时间为空："+startCreateTime);
        }
        endCreateTime = endCreateTime+" 23:59:59";
        Map paramsMap = new HashMap();
        paramsMap.put("sort","sort_number");
        paramsMap.put("order","asc");
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);
        list = deviceService.list4app(paramsMap);
        ExcelUtils.export(response,"设备导出",list, DeviceVO.class);
    }

    @ApiOperation(value = "获取最大设备编号")
    @GetMapping("/getMaxModel")
    public JsonResult getMaxModel(Long devModelId) {
        return deviceService.getMaxModel(devModelId);
    }
}
